<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <tree-tools :is-root="true" :obj="companyInfo" @add-dept="onAdd" />

        <!-- 树形结构 -->
        <el-tree :data="treeData" :props="defaultProps" :default-expand-all="true">

          <tree-tools slot-scope="{data}" :obj="data" @add-dept="onAdd" @on-edit="onEdit" />

        </el-tree>
      </el-card>
    </div>

    <add-dept
      ref="depts"
      v-model="addDialogVisible"
      :node="treeNode"
      @add-success="loadDepartmentList"
      @edit-success="loadDepartmentList"
    />

  </div>
</template>

<script>
import TreeTools from './components/TreeTools.vue'
import { getDepartmentList } from '@/api/department'
import { transListToTree } from '@/utils/index'
import AddDept from './components/add-dept.vue'
export default {
  name: 'Departments',
  components: { TreeTools, AddDept },
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      companyInfo: {
        name: '传智播客',
        manager: '负责人',
        id: ''
      },
      addDialogVisible: false,
      treeNode: {}
    }
  },

  created() {
    this.loadDepartmentList()
  },

  methods: {
    // 加载并保存组织架构数据
    async loadDepartmentList() {
      const res = await getDepartmentList()
      this.treeData = transListToTree('', res.depts)
      console.log(this.treeData)
    },
    // 点击添加子部门
    onAdd(data) {
      // 显示弹层
      this.addDialogVisible = true
      this.treeNode = data
      console.log(this.treeNode)
    },
    // 点击查看部门
    onEdit(data) {
      // 显示弹层
      this.addDialogVisible = true
      // 数据传给子组件做校验
      this.treeNode = data
      // 获取最新的数据渲染到表单
      this.$refs.depts.getDeptsInfo(data.id)
    }
  }
}
</script>

<style scoped lang='less'>

</style>
